<?php

namespace App\Jobs;

use App\Model\Messages;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use App\Model\Users;
use WebSocket\Client;

class sendMessage implements ShouldQueue
{

    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    protected $from_user;
    protected $to_user;
    protected $message;
    protected $client;
    /**
     * Create a new job instance.
     * @param Users $from_user 发送方
     * @param Users $to_user 接收方
     * @param Messages $message 消息
     * @return void
     */
    public function __construct(Users $from_user, Users $to_user, Messages $message)
    {
        $this->message = $message;
        $this->to_user = $to_user;
        $this->from_user = $from_user;
        $this->client = new Client('ws://127.0.0.1:1024');
    }
    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        try{

            $this->client->send(json_encode([
                'type'=>'send_to_friend',
                'friend_id'=>$this->to_user->id,
                'msg'=>$this->message->content,
                'from'=>$this->from_user->user_name
            ]));
            $this->client->close();
            $this->message->status = '1';
            $this->message->save();
        } catch (\Exception $exception)
        {

        }

    }
}
